<template>
    <view :style="{ '--color': color }" v-if="pageData">
        <status-bar title="分享"></status-bar>

        <view class="Wrapper">
            <view class="Income">预计收入佣金￥{{ pageData.myData.income }}</view>
            <view class="Shop">
                <image :src="$imgUrls(pageData.img)" mode="aspectFill" class="Img"></image>
                <view class="content">
                    <text class="title ellipsis_2">{{ pageData.name }}</text>
                    <view class="row j-sb a-center">
                        <view class="price color_ff4 bold500">
                            <text class="size22 m-top6">￥</text>
                            <text class="size36">{{ pageData.price }}</text>
                        </view>
                        <view class="der">
                            {{ buttonTxt.buyTitle }}
                            <store-product
                                class="store-product"
                                :product-id="pageData.product_id"
                                :appid="pageData.shop_appid"
                                :product-promotion-link="pageData.upTeamData.promotion_link"
                            ></store-product>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!--  编辑文案 -->
        <view class="Copywriting">
            <text class="black size30 bold500">编辑文案</text>
            <text class="color_99 size26 m-top20">推荐文案</text>
            <textarea placeholder="请输入文案" class="Textarea" v-model="copywriter" />
            <view class="Screen">
                <view class="list" v-for="(item, index) in screenData" :key="index">
                    <view class="Dot" :class="{ active: item.select == 1 }" @click="change(item)">
                        <view class="iconfont icon-xuanzhong size24 white"></view>
                    </view>
                    <text class="color_66 size28 m-left10">{{ item.name }}</text>
                </view>
            </view>
        </view>

        <!-- 选择素材 -->
        <view class="Material">
            <text class="black size30 bold500">选择素材</text>
            <scroll-view scroll-x="true" class="materialScroll nowrap">
                <view class="list" v-for="(item, index) in atlas" :key="index">
                    <image :src="$imgUrls(item.img)" mode="aspectFill" class="wh bor_radius_10"></image>
                    <view class="Dot" @click.stop="changeSelect(item)">
                        <view class="iconfont icon-xuanzhong size24 white" v-if="item.select"></view>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 推广口令 -->
        <view class="shibboleth">
            <view class="row j-sb a-center">
                <text class="black size30 bold500">推广口令</text>
                <view class="copyShibb" @click="$pop.setClip(pageData.myData.short_link)">复制口令</view>
            </view>
            <view class="Textarea">{{ pageData.myData.short_link }}</view>
        </view>

        <view class="footer">
            <view class="Box">
                <view class="copyBox">
                    <view class="list" @click="$pop.setClip(pageData.myData.short_link)">
                        <view class="boi">
                            <view class="iconfont icon-kouling black size24"></view>
                        </view>
                        <text class="name">复制口令</text>
                    </view>
                    <view class="list" @click="$pop.setClip(copywriter)">
                        <view class="boi">
                            <view class="iconfont icon-wenan black size24"></view>
                        </view>
                        <text class="name">复制文案</text>
                    </view>
                    <view class="list" @click="savaImage">
                        <view class="iconfont icon-tupian2 black size40"></view>
                        <text class="name">保存图片</text>
                    </view>
                </view>

                <view class="fot">
                    <view class="list color" @click="SaveShare">{{ buttonTxt.copyTitle }}</view>
                    <view class="list Poster" @click="showPoseter = true">{{ buttonTxt.shareImgTitle }}</view>
                </view>
            </view>
        </view>

        <u-popup :show="show" mode="center" @close="show = false" :round="10" closeable>
            <view class="u-popup">
                <text class="title">一键保存分享</text>
                <text class="deratxt">分享素材采集中,请稍后...</text>
                <view class="conSu">
                    <view class="list">
                        <view class="d-flex a-center">
                            <view class="doin">
                                <view class="iconfont icon-wenben size46 white"></view>
                            </view>
                            <text class="color_33 size28 m-left20">复制文案</text>
                        </view>
                        <view class="d-flex a-center">
                            <view class="iconfont icon-xuanzhong size32 color_16d"></view>
                            <text class="color_16d size26">复制成功</text>
                        </view>
                    </view>

                    <view class="list">
                        <view class="d-flex a-center">
                            <view class="doin">
                                <view class="iconfont icon-wenben size46 white"></view>
                            </view>
                            <text class="color_33 size28 m-left20">保存图片</text>
                        </view>
                        <view class="d-flex a-center" :class="downloadCount === totalImages ? 'color_16d' : 'color_99'">
                            <view class="iconfont icon-xuanzhong size32" :class="{ color_16d: downloadCount === totalImages }"></view>
                            <text class="size26" v-if="downloadCount === totalImages">保存完成</text>
                            <text class="size26" v-else>保存中({{ downloadCount }}/{{ totalImages }})</text>
                        </view>
                    </view>
                </view>
            </view>
        </u-popup>

        <u-popup :show="showPoseter" :round="10" mode="center" @close="showPoseter = false" closeable>
            <view class="popupPoseter">
                <text class="title">海报分享</text>
                <image :src="$imgUrls(posterPicture)" mode="widthFix" show-menu-by-longpress class="rows m-top30"></image>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    import Api from '@/common/Api.js';
    export default {
        data() {
            return {
                img: 'https://msraimgcdn.mogoie.com/6099/1691738405248.png',
                screenData: [
                    {
                        name: '到手价',
                        select: 1,
                        type: 1
                    },
                    {
                        name: '下单链接',
                        select: 1,
                        type: 2
                    }
                ],
                pageData: '',
                copywriter: '',
                atlas: [],
                show: false,
                downloadCount: 0,
                totalImages: 0,
                posterPicture: '',
                showPoseter: false, // 海报图
                openBusinessView: {
                    businessType: '',
                    queryString: ''
                },
                extraData: {
                    headSupplierAppid: '', // 需要填入您的机构appid
                    commissionType: 1, // 1代表机构自己分佣
                    commissionRatio: 0 // 机构自己分佣时设为0
                },
                buttonTxt: ''
            };
        },
        onLoad(opt) {
            if (opt.goods_id) this.goods_id = opt.goods_id;
            this.getGoodsShareInfo();
            this.getShareImg();
        },
        onShow() {
            this.getUserBindInfo();
        },
        methods: {
            getGoodsShareInfo() {
                this.$http
                    .post({
                        url: '/weChatStoreApi/getGoodsShareInfo',
                        data: {
                            goods_id: this.goods_id
                        }
                    })
                    .then((res) => {
                        if (res.errcode != 100) return this.$Toast(res.msg);
                        if (res.button) this.buttonTxt = res.button;
                        const result = res.data;
                        const atlas = result.atlas;
                        let atlasData = [];

                        atlas.forEach((n) => {
                            const obj = {
                                img: '',
                                select: true
                            };
                            obj.img = n;
                            atlasData.push(obj);
                        });
                        this.atlas = atlasData;

                        this.pageData = result;
                        this.shareText();
                    });
            },

            getShareImg() {
                this.$http
                    .post({
                        url: '/singleSaleApi/getShareImg',
                        data: {
                            id: this.goods_id,
                            type: 2
                        }
                    })
                    .then((res) => {
                        if (res.code != 100) return this.$Toast(res.msg);
                        this.posterPicture = res.data;
                    });
            },

            changeSelect(Item) {
                Item.select = !Item.select;
            },

            async Binding() {
                const myData = this.pageData.myData;
                const upTeamData = this.pageData.upTeamData.user_info;
                if (this.pageData.buy_verification == 1 && !myData.sharer_appid) {
                    const reuslt = await this.$Modals('您还未授权成为推客', '授权成为推客后才可购买');
                    if (reuslt) this.$pop.openBusinessView(this.openBusinessView.businessType, this.openBusinessView.queryString, this.extraData);
                    return;
                }
                this.$pop.toUserProfile(upTeamData.finder_id);
            },

            SaveShare() {
                this.show = true;
                // 第一步：复制文案
                this.$pop.setClip(this.copywriter);

                // 获取选中的图片
                const selectedImages = this.atlas.filter((item) => item.select).map((item) => item.img);

                // 重置下载计数
                this.downloadCount = 0;
                this.totalImages = selectedImages.length;

                // 如果没有选中的图片，直接返回
                if (this.totalImages === 0) {
                    this.$Toast('请选择要保存的图片');
                    return;
                }

                // 第二步：下载并保存选中的图片
                selectedImages.forEach((img) => {
                    uni.downloadFile({
                        url: this.$imgUrls(img),
                        success: (res) => {
                            if (res.statusCode === 200) {
                                uni.saveImageToPhotosAlbum({
                                    filePath: res.tempFilePath,
                                    success: () => {
                                        this.downloadCount++;
                                    },
                                    fail: () => {
                                        console.log('保存失败');
                                    }
                                });
                            }
                        },
                        fail: () => {
                            console.log('下载失败');
                        }
                    });
                });
            },

            savaImage() {
                // 获取选中的图片
                const selectedImages = this.atlas.filter((item) => item.select).map((item) => item.img);
                if (selectedImages.length === 0) {
                    return this.$Toast('请选择要保存的图片');
                }

                // 保存多张图片
                selectedImages.forEach((img) => {
                    console.log(this.$imgUrls(img));
                    uni.downloadFile({
                        url: this.$imgUrls(img),
                        success: (res) => {
                            if (res.statusCode === 200) {
                                uni.saveImageToPhotosAlbum({
                                    filePath: res.tempFilePath,
                                    success: () => {
                                        this.$Toast('保存成功');
                                    },
                                    fail: () => {
                                        this.$Toast('保存失败');
                                    }
                                });
                            } else {
                                this.$Toast('下载失败');
                            }
                        },
                        fail: () => {
                            this.$Toast('下载失败');
                        }
                    });
                });
            },

            shareText() {
                const share_text = this.pageData.share_text;
                const price = `【到手价】${this.pageData.price}元`;
                const linke = `【下单链接】${this.pageData.myData.short_link}`;
                const result = `${share_text}\n${price}\n${linke}`;
                this.copywriter = result;
            },
            change(item) {
                item.select = item.select == 1 ? 0 : 1;
                const share_text = this.pageData.share_text;
                const price = `【到手价】${this.pageData.price}元`;
                const linke = `【下单链接】${this.pageData.myData.short_link}`;

                // 找到另一个选项的状态
                const otherItem = this.screenData.find((i) => i.type !== item.type);
                let result = share_text;

                // 处理价格显示
                if ((item.type === 1 && item.select === 1) || (otherItem.type === 1 && otherItem.select === 1)) {
                    result += '\n' + price;
                }

                // 处理链接显示
                if ((item.type === 2 && item.select === 1) || (otherItem.type === 2 && otherItem.select === 1)) {
                    result += '\n' + linke;
                }

                this.copywriter = result;
            },
            async getUserBindInfo() {
                const requestResult = await Api.getUserBindInfo();
                const result = requestResult.data;
                if (requestResult.user_status == 4) return;
                this.openBusinessView = {
                    businessType: result.businessType,
                    queryString: result.queryString
                };
                this.extraData = {
                    headSupplierAppid: result.extraData.headSupplierAppid,
                    commissionType: result.extraData.commissionType,
                    commissionRatio: result.extraData.commissionRatio
                };
            }
        },
        computed: {
            ...mapState(['color'])
        }
    };
</script>

<style lang="scss">
    page {
        background-color: $page;
        padding-bottom: calc(env(safe-area-inset-bottom) + 280rpx);
    }
</style>
<style lang="scss" scoped>
    .popupPoseter {
        width: 600rpx;
        padding: 24rpx;
        display: flex;
        flex-direction: column;
        .title {
            color: #000;
            font-size: 32rpx;
            font-weight: 500;
        }
    }
    .u-popup {
        width: 690rpx;
        padding: 30rpx 20rpx 60rpx 20rpx;
        display: flex;
        flex-direction: column;
        .title {
            color: #000;
            font-size: 30rpx;
            text-align: center;
            font-weight: 500;
        }
        .deratxt {
            color: #999;
            font-size: 26rpx;
            text-align: center;
            margin-top: 24rpx;
        }
        .conSu {
            width: 100%;
            margin-top: 30rpx;
            border-top: 1px solid #ccc;
            display: flex;
            flex-direction: column;
            .list {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 36rpx;
                .doin {
                    width: 70rpx;
                    height: 70rpx;
                    background-color: var(--color);
                    border-radius: 50%;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
            }
        }
    }
    .shibboleth {
        width: 700rpx;
        background-color: #fff;
        margin: 24rpx auto 0;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        padding: 20rpx 20rpx 24rpx 20rpx;
        .copyShibb {
            padding: 10rpx 24rpx;
            border-radius: 30rpx;
            background-color: var(--color);
            color: #fff;
            font-size: 26rpx;
        }
        .Textarea {
            width: 100%;
            height: 120rpx;
            background-color: #f7f8fa;
            border: 1px solid #f2f2f2;
            padding: 38rpx 20rpx;
            border-radius: 10rpx;
            margin-top: 20rpx;
            font-size: 26rpx;
            color: #666;
        }
    }
    .Material {
        width: 700rpx;
        background-color: #fff;
        margin: 24rpx auto 0;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        padding: 20rpx 20rpx 24rpx 20rpx;
        .materialScroll {
            width: 100%;
            margin-top: 20rpx;
            .list {
                display: inline-block;
                width: 180rpx;
                height: 180rpx;
                border-radius: 10rpx;
                overflow: hidden;
                margin-right: 20rpx;
                position: relative;
                .Dot {
                    width: 40rpx;
                    height: 40rpx;
                    border-radius: 50%;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background-color: var(--color);
                    border: 1px solid var(--color);
                    position: absolute;
                    top: 10rpx;
                    right: 10rpx;
                }
            }
            .list:last-child {
                margin-right: 0;
            }
        }
    }
    .Copywriting {
        width: 700rpx;
        background-color: #fff;
        margin: 24rpx auto 0;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        padding: 20rpx 20rpx 24rpx 20rpx;
        .Textarea {
            width: 100%;
            background-color: #f7f8fa;
            border: 1px solid #f2f2f2;
            padding: 30rpx 10rpx;
            border-radius: 10rpx;
            margin-top: 20rpx;
            font-size: 24rpx;
            color: #515254;
            height: 200rpx;
        }
        .Screen {
            width: 100%;
            margin-top: 24rpx;
            display: flex;
            .list {
                display: flex;
                align-items: center;
                margin-right: 24rpx;
                .Dot {
                    width: 40rpx;
                    height: 40rpx;
                    border-radius: 50%;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    border: 1px solid #ccc;
                }
                .active {
                    background-color: var(--color);
                    border: 1px solid var(--color);
                }
            }
        }
    }
    .Wrapper {
        width: 700rpx;
        background-color: #fff;
        margin: 24rpx auto 0;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .Income {
            width: 100%;
            padding: 20rpx;
            background-color: var(--color);
            color: #fff;
            font-size: 28rpx;
        }
        .Shop {
            width: 100%;
            padding: 20rpx;
            display: flex;
            align-items: center;
            .Img {
                width: 160rpx;
                height: 160rpx;
                border-radius: 10rpx;
                margin-right: 24rpx;
            }
            .content {
                flex: 1;
                height: 160rpx;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                .title {
                    color: #000;
                    font-size: 30rpx;
                    font-weight: 500;
                }
                .der {
                    width: 120rpx;
                    height: 60rpx;
                    border-radius: 10rpx;
                    background-color: var(--color);
                    font-size: 28rpx;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    color: #fff;

                    position: relative;
                    overflow: hidden;
                    .store-product {
                        width: 100%;
                        height: 100%;
                        position: absolute;
                        top: 0;
                        left: 0;
                        z-index: 110;
                        opacity: 0;
                    }
                }
            }
        }
    }
    .footer {
        width: 100%;
        background-color: #fff;
        position: fixed;
        bottom: 0;
        left: 0;
        z-index: 100;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        .Box {
            width: 100%;
            height: 220rpx;
            display: flex;
            flex-direction: column;
            padding: 24rpx 0;
            display: flex;
            flex-direction: column;
            .copyBox {
                width: 100%;
                padding: 0 24rpx;
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                .list {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    .boi {
                        width: 34rpx;
                        height: 34rpx;
                        border: 1px solid #000;
                        border-radius: 6rpx;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        overflow: hidden;
                    }
                    .name {
                        color: var(--color);
                        font-size: 28rpx;
                        margin-left: 10rpx;
                        font-weight: 500;
                    }
                }
            }
            .fot {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 24rpx;
                margin-top: 38rpx;
                .list {
                    width: 340rpx;
                    height: 90rpx;
                    border-radius: 45rpx;
                    border: 1px solid var(--color);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-size: 32rpx;
                    font-weight: 500;
                }
                .Poster {
                    background-color: var(--color);
                    color: #fff;
                }
            }
        }
    }
</style>
